import { ExclamationCircleOutlined } from '@ant-design/icons'
import axios from '@/http'
import Remark from '../remark/remark'
import { Avatar, Comment, Empty, message, Modal, Spin } from 'antd'
import { useContext, useEffect, useState } from 'react'
import { TComment } from '@type'
import { formatTime } from '@/util'
import { AppContext } from '@/App'
const { confirm } = Modal

const Comments: React.FC<{ id: number }> = ({ id }) => {
  const [commentList, setCommentList] = useState<TComment[] | undefined>()
  const [Loading, setLoading] = useState<boolean>(false)
  const {
    store: { username }
  } = useContext(AppContext)
  useEffect(() => {
    getCommentList()
  }, [])
  const getCommentList = () => {
    setLoading(true)
    axios
      .get('/comment/search', {
        params: {
          blogId: id
        }
      })
      .then(res => {
        res.data.error === -1 ? setCommentList(res.data.data) : setCommentList([])
      })
      .finally(() => {
        setLoading(false)
      })
  }
  const showDeleteConfirm = (id: number) => {
    confirm({
      title: '删除评论?',
      icon: <ExclamationCircleOutlined />,
      content: '你确定要删除该评论？',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        deleteComment(id)
      }
    })
  }
  const deleteComment = (id: number) => {
    axios
      .post('/comment/del', {
        id
      })
      .then(res => {
        console.log(res)
        if (res.data.error === -1) {
          message.success('删除成功')
          getCommentList()
        } else {
          message.error('删除失败')
        }
      })
  }
  return (
    <div style={{ maxHeight: '300px', overflow: 'auto' }}>
      {!Loading ? (
        commentList ? (
          commentList.map(item => (
            <Comment
              key={item.id}
              author={<a>{item.realname}</a>}
              avatar={<Avatar src={item.avatar} alt="Han Solo" />}
              content={<p>{item.content}</p>}
              datetime={<span>{formatTime(item.time)}</span>}
              actions={[
                <a onClick={() => showDeleteConfirm(item.id)} style={{ color: 'red' }}>
                  删除
                </a>
              ]}
            >
              <Remark blogId={id} commentId={item.id}></Remark>
            </Comment>
          ))
        ) : (
          <Empty />
        )
      ) : (
        <Spin />
      )}
    </div>
  )
}
export default Comments
